
package P346;
import java.io.*;
import java.util.*;
public class Questionthree {
	   public static void main(String args[]) {
	      File file = new File("D:/JAVA/新建文件夹/编程/shiyan3/src/P346/146页第三题.txt");
	      Scanner scanner = null;
	      double sum=0;
	      int count = 0;	      
	      try { 
	    	  scanner = new Scanner(file);
	    	  scanner.useDelimiter("[^0123456789.]+");
	          while(scanner.hasNextDouble()){
	        	  double price = scanner.nextDouble();
	        	  count++;
                  sum += price;
	          }	          
	          if(count >0) {
	        	  double average = sum/count;
	        	  String Average = String.format("%.3f",average);
	        	  System.out.println("这些商品的平均价格是（单位：元）：" + Average);
	        	  try (BufferedWriter writer = new BufferedWriter(new FileWriter(file,true))){
	        		  writer.newLine();
	        		  writer.write("这些商品的平均价格是（单位：元）：" + Average + "YUAN");
	        	  }
	          }else {
	        	  System.out.println("没有找到有效的数据");
	          }
	      } catch (FileNotFoundException e) {
	    	  System.out.println("文件未找到：" + e.getMessage());
	      } catch (IOException e) {
	    	  System.out.println("写入文件时候出错误：" + e.getMessage());
	      } finally {
	    	  if (scanner != null) {
	    		  scanner.close();	    		  
	    	  }
	      }
	      
	  }
}